﻿using System;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using WMSABL.SY;
using WMSAML.SY;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;
/****************************************
** 作者: LH
** 时间: 2017/02/22
** 系统登录
*****************************************/
namespace ElectronicWMSA
{
    public partial class Login : Form
    {
        #region 
        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_MINIMIZEBOX = 0x00020000;
                CreateParams cp = base.CreateParams;
                cp.Style = cp.Style | WS_MINIMIZEBOX;
                return cp;
            }
        }
        TUsers_BLL bll_TUser = new TUsers_BLL();
        TUsers_Entity entity_TUser = new TUsers_Entity();
        TSystemRegistBLL bll_SystemRegist = new TSystemRegistBLL();
        private string _Version = "";
        public Login()
        {
            InitializeComponent();
        }
        private void Login_Load(object sender, EventArgs e)
        {
            btnLogin.Focus(); GetXML();
        }
        private void GetXML()
        {
            if (File.Exists("VersionConfig.xml"))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load("VersionConfig.xml");
                foreach (XmlNode item in xmldoc.GetElementsByTagName("V"))
                {
                    foreach (XmlNode items in item.ChildNodes)
                    {
                        if (items.Name == "Num")
                            _Version = items.InnerText.Trim();
                    }
                }
            }
            if (!File.Exists("configXml.xml"))
            {
                XmlDocument doc = new XmlDocument();
                XmlElement Root = doc.CreateElement("login");
                doc.AppendChild(Root);
                doc.Save(Application.StartupPath + "\\configXml.xml");
            }
            else
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load("configXml.xml");
                XmlElement root = xmldoc.DocumentElement;
                XmlNode xn = xmldoc.LastChild.LastChild;
                if (root.ChildNodes.Count > 10)
                {
                    root.RemoveChild(xn);
                }
                xmldoc.Save("configXml.xml");
                foreach (XmlNode item in xmldoc.GetElementsByTagName("loginer"))
                {
                    foreach (XmlNode items in item.ChildNodes)
                    {
                        if (items.Name == "loginName")
                            cbxUserName.Items.Add(items.InnerText);
                    }
                }
                if (cbxUserName.Items.Count > 0)
                {
                    cbxUserName.SelectedIndex = 0;
                }
                if (this.cbxUserName.Items.Count > 0)
                    this.btnClearUserInfo.Visible = true;
            }
            if (File.Exists("SytemConfig.xml"))
            {
                string APPIP = "", APPDB = "", APPUR = "", APPPD = "";
                string SAPIP = "", SAPDB = "", SAPUR = "", SAPPD = "";
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load("SytemConfig.xml");
                foreach (XmlNode item in xmldoc.GetElementsByTagName("DOC"))
                {
                    foreach (XmlNode items in item.ChildNodes)
                    {
                        if (items.Name == "SYSTEMNAME")
                            EWMSAClass.SYSTEMNAME = items.InnerText.Trim();
                        else if (items.Name == "NUMBER")
                            EWMSAClass.WMS_Number = items.InnerText.Trim();
                        else if (items.Name == "CUSTOMERNAME")
                            EWMSAClass.CUSTOMERNAME = items.InnerText.Trim();
                        else if (items.Name == "VERSION")
                            EWMSAClass.VERSION = items.InnerText.Trim();
                        else if (items.Name == "APPLICATIONPROGRAMIP")
                        {
                            APPIP = items.InnerText.Trim();
                            WMSADBUtility.Database.ServerAddress = APPIP;
                        }
                        else if (items.Name == "APPLICATIONPROGRAMDB")
                        {
                            APPDB = items.InnerText.Trim();
                            WMSADBUtility.Database.DBName = "WMSA17DB";
                        }
                        else if (items.Name == "APPLICATIONPROGRAMUR")
                        {
                            APPUR = items.InnerText.Trim();
                        }
                        else if (items.Name == "APPLICATIONPROGRAMPD")
                        {
                            if (items.InnerText.Trim() != "")
                                APPPD = ElectronicWMSA.Comm.ClassFiles.PCInfoClass.Decryption(items.InnerText.Trim(), "/*-./.,@");
                        }

                        else if (items.Name == "SAPIP")
                            SAPIP = items.InnerText.Trim();
                        else if (items.Name == "SAPDB")
                            SAPDB = items.InnerText.Trim();
                        else if (items.Name == "SAPUSER")
                            SAPUR = items.InnerText.Trim();
                        else if (items.Name == "SAPPWD")
                        {
                            if (items.InnerText.Trim() != "")
                                SAPPD = PCInfoClass.Decryption(items.InnerText.Trim(), "/*-./.,@");
                        }
                    }
                }
                WMSADBUtility.Database.ConnString = "         server=" + APPIP + ";database=" + APPDB + ";uid=" + APPUR + ";pwd=" + APPPD + ";";
                WMSADBUtility.DbHelperSAP.connectionString = "server=" + SAPIP + ";database=" + SAPDB + ";uid=" + SAPUR + ";pwd=" + SAPPD + ";";
            }
        }
        #endregion

        #region Login
        private void btnLogin_Click(object sender, EventArgs e)
        {
            WaitingBoxFrm wf = new WaitingBoxFrm((obj, args) => { Thread.Sleep(500); Conn(); }, 30); wf.ShowDialog(this);

            if (IsConnection)
            {
                TAutoFiles_BLL bll_TAutoFiles = new TAutoFiles_BLL();
                TAutoFiles_Entity entity_TAutoFiles = new TAutoFiles_Entity();
                entity_TAutoFiles = bll_TAutoFiles.GetEntity(0);
                if (entity_TAutoFiles != null && _Version != "" && _Version != entity_TAutoFiles.Vison) // 判断是否有更新
                {
                    MessageClass.warning("有新版本升级！");
                    XmlDocument doc = new XmlDocument();
                    string strFileName = Application.StartupPath + "\\SytemConfig.xml";
                    doc.Load(strFileName);
                    XmlNodeList nodeList = doc.SelectSingleNode("DOC").ChildNodes;
                    foreach (XmlNode xn in nodeList)
                    {
                        if (xn.Name == "VERSION")
                            xn.InnerText = entity_TAutoFiles.Vison;
                    }
                    doc.Save(strFileName);
                    System.Diagnostics.Process.Start(Application.StartupPath + "\\Autoupdater.exe");
                }
            }

            #region
            string login_Name = cbxUserName.Text.Trim();
            string pwd = txtPWD.Text.Trim();
            if (login_Name == "")
            {
                this.labShow.Text = "请输入用户名！";
                this.cbxUserName.Focus();
                return;
            }
            if (pwd == "")
            {
                this.labShow.Text = "请输入密码！";
                this.txtPWD.Focus();
                return;
            }
            #endregion

            if (!IsConnection)
            {
                MessageClass.error("服务器连接失败！");
                return;
            }
            try
            {
                #region 验证用户名/密码
                entity_TUser = bll_TUser.GetEntityByName(login_Name);
                if (entity_TUser == null)
                {
                    this.labShow.Text = "用户名不存在，请重新输入！";
                    this.cbxUserName.Focus();
                    return;
                }
                if (entity_TUser.EnableStatus == 0)
                {
                    this.labShow.Text = "该用户已被注销，不能使用！";
                    this.cbxUserName.Focus();
                    return;
                }
                pwd = DesMd5.MD5Encrypt(pwd);
                if (!bll_TUser.Validate_Login(login_Name, pwd))
                {
                    this.labShow.Text = "登录失败，密码错误！";
                    this.cbxUserName.Focus();
                    return;
                }
                #endregion

                #region 是否记住登录
                if (this.checkBox1.Checked == true)
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load("configXml.xml");
                    XmlNode Node = xmldoc.DocumentElement;
                    string loginUserNames = login_Name;
                    string loginPWDs = PCInfoClass.Encryption(txtPWD.Text.Trim(), "/*-./.,@");
                    XmlElement xmlloginUserName = xmldoc.CreateElement("loginer");
                    XmlElement xmlName = xmldoc.CreateElement("loginName");
                    xmlName.InnerText = loginUserNames;
                    XmlElement xmlPWD = xmldoc.CreateElement("loginPWD");
                    xmlPWD.InnerText = loginPWDs;
                    XmlNode node = xmldoc.SelectSingleNode("//loginer[loginName='" + loginUserNames + "']");
                    if (node == null)
                    {
                        xmlloginUserName.PrependChild(xmlPWD);
                        xmlloginUserName.PrependChild(xmlName);
                        Node.PrependChild(xmlloginUserName);
                    }
                    else
                    {
                        XmlNodeList nodes;
                        XmlElement root = xmldoc.DocumentElement;
                        nodes = root.SelectNodes("//loginer[loginName='" + loginUserNames + "']");
                        foreach (XmlNode node1 in nodes)
                        {
                            root.RemoveChild(node1);
                        }
                        xmlloginUserName.PrependChild(xmlPWD);
                        xmlloginUserName.PrependChild(xmlName);
                        Node.PrependChild(xmlloginUserName);
                    }
                    xmldoc.Save("configXml.xml");
                }
                else
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load("configXml.xml");
                    XmlNode Node = xmldoc.DocumentElement;
                    string loginUserNames = login_Name;
                    string loginPWDs = null;
                    XmlElement xmlloginUserName = xmldoc.CreateElement("loginer");
                    XmlElement xmlName = xmldoc.CreateElement("loginName");
                    xmlName.InnerText = loginUserNames;
                    XmlElement xmlPWD = xmldoc.CreateElement("loginPWD");
                    xmlPWD.InnerText = loginPWDs;
                    XmlNode node = xmldoc.SelectSingleNode("//loginer[loginName='" + loginUserNames + "']");
                    if (node == null)
                    {
                        xmlloginUserName.PrependChild(xmlPWD);
                        xmlloginUserName.PrependChild(xmlName);
                        Node.PrependChild(xmlloginUserName);
                    }
                    else
                    {
                        XmlNodeList nodes;
                        XmlElement root = xmldoc.DocumentElement;
                        nodes = root.SelectNodes("//loginer[loginName='" + loginUserNames + "']");
                        foreach (XmlNode node1 in nodes)
                        {
                            root.RemoveChild(node1);
                        }
                        xmlloginUserName.PrependChild(xmlPWD);
                        xmlloginUserName.PrependChild(xmlName);
                        Node.PrependChild(xmlloginUserName);
                    }
                    xmldoc.Save("configXml.xml");
                }
                #endregion

                #region 存储和更改用户当前信息
                SystemVariable.User_ID = entity_TUser.User_id;
                SystemVariable.User_Name = entity_TUser.Username;
                SystemVariable.Login_Name = entity_TUser.Login_name;

                SystemVariable.Vaidation(entity_TUser.User_id);

                entity_TUser = bll_TUser.GetEntityByID(entity_TUser.User_id);
                entity_TUser.Last_login_time = entity_TUser.Login_time;
                entity_TUser.Login_time = DateTime.Now;
                entity_TUser.Count = entity_TUser.Count + 1;
                entity_TUser.LoginIP = PCInfoClass.GetFirstIP().ToString();
                entity_TUser.LoginStatus = 1;
                bll_TUser.Update(entity_TUser);
                #endregion

                this.Hide();
                SystemVariable.AddLogInfo("系统登录", "操作员：【" + SystemVariable.Login_Name + "】登录系统");
                Main frm = new Main();
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                ErrorLogLoad.ErrorLogInfo(ex.Message.ToString());
                MessageClass.error("系统操作异常？");
            }
        }
        public bool IsConnection = false;
        public void Conn()
        {
            if (bll_SystemRegist.ConnectionSQL()) this.IsConnection = true;
        }
        #endregion

        #region  Pwd
        public void DBind_Pwd()
        {
            if (checkBox1.Checked == true)
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load("configXml.xml");
                XmlNode Node = xmldoc.DocumentElement;
                string loginUserNames = cbxUserName.Text.Trim();
                string loginPWDs = PCInfoClass.Encryption(txtPWD.Text.Trim(), "/*-./.,@");
                XmlElement xmlloginUserName = xmldoc.CreateElement("loginer");
                XmlElement xmlName = xmldoc.CreateElement("loginName");
                xmlName.InnerText = loginUserNames;
                XmlElement xmlPWD = xmldoc.CreateElement("loginPWD");
                xmlPWD.InnerText = loginPWDs;
                XmlNode node = xmldoc.SelectSingleNode("//loginer[loginName='" + loginUserNames + "']");
                if (node == null)
                {
                    xmlloginUserName.PrependChild(xmlPWD);
                    xmlloginUserName.PrependChild(xmlName);
                    Node.PrependChild(xmlloginUserName);
                }
                else
                {
                    XmlNodeList nodes;
                    XmlElement root = xmldoc.DocumentElement;
                    nodes = root.SelectNodes("//loginer[loginName='" + loginUserNames + "']");
                    foreach (XmlNode node1 in nodes)
                    {
                        root.RemoveChild(node1);
                    }
                    xmlloginUserName.PrependChild(xmlPWD);
                    xmlloginUserName.PrependChild(xmlName);
                    Node.PrependChild(xmlloginUserName);
                }
                xmldoc.Save("configXml.xml");
            }
            else
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load("configXml.xml");

                XmlNode Node = xmldoc.DocumentElement;

                string loginUserNames = cbxUserName.Text.Trim();
                string loginPWDs = null;
                XmlElement xmlloginUserName = xmldoc.CreateElement("loginer");
                XmlElement xmlName = xmldoc.CreateElement("loginName");
                xmlName.InnerText = loginUserNames;
                XmlElement xmlPWD = xmldoc.CreateElement("loginPWD");
                xmlPWD.InnerText = loginPWDs;
                XmlNode node = xmldoc.SelectSingleNode("//loginer[loginName='" + loginUserNames + "']");
                if (node == null)
                {
                    xmlloginUserName.PrependChild(xmlPWD);
                    xmlloginUserName.PrependChild(xmlName);
                    Node.PrependChild(xmlloginUserName);
                }
                else
                {
                    XmlNodeList nodes;
                    XmlElement root = xmldoc.DocumentElement;
                    nodes = root.SelectNodes("//loginer[loginName='" + loginUserNames + "']");
                    foreach (XmlNode node1 in nodes)
                    {
                        root.RemoveChild(node1);
                    }
                    xmlloginUserName.PrependChild(xmlPWD);
                    xmlloginUserName.PrependChild(xmlName);
                    Node.PrependChild(xmlloginUserName);
                }
                xmldoc.Save("configXml.xml");
            }
        }
        #endregion

        #region GetUserNameXml
        private void cbxUserName_SelectedIndexChanged(object sender, EventArgs e)
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load("configXml.xml");
            string cmbUserName = cbxUserName.Text.Trim();
            XmlNodeList nodes;
            XmlElement root = xmldoc.DocumentElement;
            nodes = root.SelectNodes("//loginer[loginName='" + cmbUserName + "']");
            string strn = null;
            string strpwd = null;
            foreach (XmlNode item in nodes)
            {
                XmlElement xe = (XmlElement)item;
                XmlNodeList xnlist = xe.ChildNodes;
                foreach (XmlNode items in xnlist)
                {
                    XmlElement xelement = (XmlElement)items;
                    if (xelement.LocalName == "loginName")
                    {
                        strn = xelement.InnerText;
                        if (strn == cmbUserName)
                        {
                            XmlNode xmlnode = xelement.NextSibling;
                            strpwd = PCInfoClass.Decryption(xmlnode.InnerText, "/*-./.,@");
                            if (strpwd != "")
                                checkBox1.Checked = true;
                        }
                    }
                }
            }
            txtPWD.Text = strpwd;
        }
        #endregion

        #region KeyDown
        private void txtPWD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                this.btnLogin_Click(sender, e);
            }
        }
        private void cbxUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                this.btnLogin_Click(sender, e);
            }
            if (e.KeyValue != 13)
            {
                this.txtPWD.Text = "";
                this.checkBox1.Checked = false;
            }
        }
        #endregion

        #region
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.cbxUserName.Text = "";
            this.txtPWD.Text = "";
            this.cbxUserName.Focus();
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        #region
        Point downPoint;
        private void panLogin_MouseDown(object sender, MouseEventArgs e)
        {
            downPoint = new Point(e.X, e.Y);
        }
        private void panLogin_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - downPoint.X,
                    this.Location.Y + e.Y - downPoint.Y);
            }
        }
        #endregion

        private void button1_MouseEnter(object sender, EventArgs e)
        {
            labShow.Text = "清除所有记住的用户登录信息！";
        }

        private void button1_MouseLeave(object sender, EventArgs e)
        {
            labShow.Text = "";
        }

        private void labConnectionSQL_Click(object sender, EventArgs e)
        {
            ServerSqlConnSet frm = new ServerSqlConnSet();
            frm.ShowDialog();
        }
        #endregion

        #region clearUsersInfo
        private void button1_Click(object sender, EventArgs e)
        {
            if (MessageClass.enquire("清空记住的用户！") == DialogResult.OK)
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load("configXml.xml");
                XmlNode Node = xmldoc.DocumentElement;
                Node.RemoveAll();
                cbxUserName.Items.Clear();
                xmldoc.Save("configXml.xml");
                cbxUserName.Text = "";
                txtPWD.Text = "";
                btnClearUserInfo.Visible = false;
            }
        }
        #endregion
    }
}
